/*
Copyright (C) 2009-2011 Xanadu Development Team

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; version 2
of the License.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

#include "provider/DataProvider.h"
#include <Winsock2.h>
#include "tools/MySQLM.h"
#include "../Connection/Acceptor.h"
#include "../Decoder/Decoder.h"
#include "net/login/PlayerLogin.h"
#include "client/Initializing.h"
#include "net/channel/PlayerHandler.h"
#include "net/channel/PlayerLoginHandler.h"
#include "net/world/Worlds.h"
#include "tools/Tools.h"
#include "scripting/AngelScriptEngine.h"

void main() {
	string title = "AlexMS";
	cout << "Starting up the server engine...";
	AngelScriptEngine::Initialize();
	Initializing::initializeSettings();
	SetConsoleTitle(title.c_str());
	cout << "Connecting to MySQL...";
	MySQL::getInstance()->connectToMySQL();
	cout << " Done!" << endl;
	try {
		Initializing::initialize();
    }
	catch(mysqlpp::BadQuery) {
		cout << endl << "Please check your database for missing tables!";
		cin.get();
		exit(1);
	}
	cout << "Loading Packets...";
	PlayerHandler::loadPackets();
	PlayerLoginHandler::loadPackets();
	cout << " Done!" << endl << "Initializing Game Entities...";
	Decoder::Initialize();
	cout << " Done!" << endl << "Connecting to Master Server..." << endl;
	Tools::randomize();
	WSADATA wsaData;
	int error = WSAStartup(MAKEWORD(2, 2), &wsaData);
	if (error != 0) {
		cout << "WSAStartup failed with error: " << error;
		cin.get();
		exit(1);
	}
	Selector* selector = new Selector();
	Worlds::getInstance()->start(selector);
	new Acceptor(8484, selector, new PlayerLoginFactory());
	cout << "The server is online and running on port 8484." << endl;
	Worlds::getInstance()->commandListener();
}
